package com.hanbo.flymouse

import android.Manifest
import android.bluetooth.BluetoothAdapter
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.widget.Button
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.ContextCompat
import com.hanbo.flymouse.hid.HidPeripheralService
import com.hanbo.flymouse.hid.HidPeripheralService.Companion.ACTION_START
import com.hanbo.flymouse.ui.TouchpadActivity

class MainActivity : ComponentActivity() {

    private val requestBluetoothPermission =
        registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { result ->
            val allGranted = result.values.all { it }
            if (!allGranted) {
                Toast.makeText(this, "需要蓝牙权限", Toast.LENGTH_SHORT).show()
            }
        }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val startBtn = Button(this).apply { text = "启动 HID 并连接" }
        val touchpadBtn = Button(this).apply { text = "进入触摸板" }

        val layout = androidx.appcompat.widget.LinearLayoutCompat(this).apply {
            orientation = androidx.appcompat.widget.LinearLayoutCompat.VERTICAL
            addView(startBtn)
            addView(touchpadBtn)
        }
        setContentView(layout)

        ensureBluetoothEnabled()
        ensurePermissions()

        startBtn.setOnClickListener {
            ContextCompat.startForegroundService(
                this,
                Intent(this, HidPeripheralService::class.java).apply { action = ACTION_START }
            )
        }
        touchpadBtn.setOnClickListener {
            startActivity(Intent(this, TouchpadActivity::class.java))
        }
    }

    private fun ensureBluetoothEnabled() {
        val adapter = BluetoothAdapter.getDefaultAdapter()
        if (adapter != null && !adapter.isEnabled) {
            startActivity(Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE))
        }
    }

    private fun ensurePermissions() {
        val perms = mutableListOf(
            Manifest.permission.BLUETOOTH,
            Manifest.permission.BLUETOOTH_ADMIN
        )
        if (Build.VERSION.SDK_INT >= 31) {
            perms += listOf(
                Manifest.permission.BLUETOOTH_CONNECT,
                Manifest.permission.BLUETOOTH_ADVERTISE
            )
        }
        requestBluetoothPermission.launch(perms.toTypedArray())
    }
}
